package org.yxing.palpalgps.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Environment;
import android.util.Log;

public class Utils {
    /**
     * get md5
     * @param str
     * @return
     */
    public static String md5(String str) {
        String data = null;
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(str.getBytes());
            byte[] messageDigest = digest.digest();
            
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString((messageDigest[i] & 0xFF | 0x100)).substring(1, 3));
            data = hexString.toString();
            
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return data;
    }
    
    /**
     * 
     * @return
     */
    public static String time() {
        return Long.toString((new Date()).getTime()).substring(0,10);
    }
    
    /**
     * 上传文件
     * @param url 地址
     * @param is 文件流
     * @param fileName 文件名称
     * @param inputName
     * @param params 参数
     * @throws IOException
     */
    public static String uploadFile(String url, InputStream is, String fileName, String inputName, List<BasicNameValuePair> params) throws IOException {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(url);
            MultipartEntity multipartEntity = new MultipartEntity();
            
            if (is != null) {
                byte[] data = IOUtils.toByteArray(is);
                InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), fileName);
                multipartEntity.addPart(inputName, isb);
            }
            
            Log.d("uploadFile", params.toString());
            for (BasicNameValuePair pair : params) 
                multipartEntity.addPart(pair.getName(), new StringBody(pair.getValue()));

            postRequest.setEntity(multipartEntity);
            HttpResponse res = httpClient.execute(postRequest);
            
            String result = null;
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = br.readLine()) != null) {
                    sb.append(line + NL);
                }
                result = sb.toString();
                br.close();
            } else {
                Log.v("uploadFile", res.getStatusLine().getStatusCode() + "");
                Log.v("uploadFile", EntityUtils.toString(res.getEntity()));
            }
            is.close();
            return result;
    }
    
    public static File getSDCardPath() {
        File path = null;
        if (hasSDCard())
            path = Environment.getExternalStorageDirectory();
        return path;
    }
    
    public static boolean hasSDCard() {
        return (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) ? true : false;
    }
    
    public static Calendar getDate(String data) {
        Calendar c = Calendar.getInstance();
        if (data != null && data.length() > 1) {
            try {
                Date date = Helper.getSimpleDateFormat().parse(data);
                c.setTime(date);
            } catch (ParseException e) {
                Log.w("getDate", e.getMessage());
            }
        }
        
        return c;
    }
    
    /**
     * request data
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String openUrl(String url, List<BasicNameValuePair> params) throws NoHttpResponseException, IOException {
        //response result
        String result = null;
        if (!url.startsWith("http://")) {
            url = Helper.getAppUrl(url);
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse resp = new DefaultHttpClient().execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStream is = resp.getEntity().getContent();
            InputStreamReader reader = new InputStreamReader(is, HTTP.UTF_8);
            char[] buf = new char[512];
            int l;
            StringBuffer buffer = new StringBuffer();
            while ((l = reader.read(buf)) != -1) {
                buffer.append(buf, 0, l);
            }
            result = buffer.toString();
            Log.d("openUrl", "url:" + url + "\nparams: " + params.toString() + "\nresult: " + result);
            is.close();
            reader.close();
        } else {
            Log.w("openUrl", url + "\n" + resp.getStatusLine().getStatusCode() + "");
        }
        return result;
    }
}
